#include <sys/time.h>
#include <time.h>
#include "rtc_misc.h"

static const uint8_t rtc_days_in_month[] = {
    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

#define LEAPS_THRU_END_OF(y) ((y)/4 - (y)/100 + (y)/400)

static inline uint8_t is_leap_year(uint32_t year)
{
    return (!(year % 4) && (year % 100)) || !(year % 400);
}

static int rtc_month_days(uint32_t month, uint32_t year)
{
    return rtc_days_in_month[month] + (is_leap_year(year) && month == 1);
}

static uint32_t mktime_local(uint32_t year, uint32_t month, uint32_t day, uint32_t hour, uint32_t minute, uint32_t second)
{
    /* 1..12 -> 11,12,1..10 */
    if (0 >= (int) (month -= 2)) {
        month += 12;	/* Puts Feb last since it has leap day */
        year -= 1;
    }

    return ((((uint32_t) (year/4 - year/100 + year/400 + 367*month/12 + day) +
                    year*365 - 719499 )*24 + hour /* now have hours */
            )*60 + minute /* now have minutes */ )*60 + second; /* finally seconds */
}

/*
 * Convert seconds since 01-01-1970 00:00:00 to Gregorian date.
 */
void rtc_to_time(uint32_t *time, rtc_time_t *tm)
{
    unsigned int month, year;
    int days;

    days = *time / 86400;
    *time -= (unsigned int) days * 86400;

    /* day of the week, 1970-01-01 was a Thursday */
    tm->wday = (days + 4) % 7;
    if (0 == tm->wday) tm->wday = 7;

    year = 1970 + days / 365;
    days -= (year - 1970) * 365
        + LEAPS_THRU_END_OF(year - 1)
        - LEAPS_THRU_END_OF(1970 - 1);
    if (days < 0) {
        year -= 1;
        days += 365 + is_leap_year(year);
    }
    tm->year = year;

    for (month = 0; month < 11; month++) {
        int newdays;

        newdays = days - rtc_month_days(month, year);
        if (newdays < 0)
            break;
        days = newdays;
    }
    tm->month = month + 1;
    tm->day = days + 1;

    tm->hour = *time / 3600;
    *time -= tm->hour * 3600;
    tm->minute = *time / 60;
    tm->second = *time - tm->minute * 60;
}

uint32_t time_to_rtc(const rtc_time_t *tm)
{
    return mktime_local(tm->year, tm->month, tm->day,
            tm->hour, tm->minute, tm->second);
}


// ##
uint32_t rtc_utc_get(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);

    return tv.tv_sec;
}

// ##
uint64_t rtc_utc_ms_get(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);

    return (tv.tv_usec / 1000) + (tv.tv_sec * 1000);
}

// ##
bool rtc_time_get(rtc_struct_t *val)
{
    if (!val)
        return false;

    rtc_time_t rtc = {0};
    time_t now = time(NULL);
    struct tm *t = gmtime(&now);

    val->year = t->tm_year + 1900;
    val->month = t->tm_mon;
    val->day = t->tm_mday;
    val->hour = t->tm_hour;
    val->minutes = t->tm_min;
    val->seconds = t->tm_sec;
    val->week = t->tm_wday;

    return true;
}